"""
日志系统模块
提供统一的日志记录功能，支持不同级别的日志输出
"""

import logging
import os
import sys
from datetime import datetime
from typing import Optional


class Logger:
    """统一的日志管理器"""
    
    _instance: Optional['Logger'] = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if self._initialized:
            return
        
        self._initialized = True
        self._setup_logging()
    
    def _setup_logging(self):
        """设置日志配置"""
        # 创建日志目录
        log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'logs')
        os.makedirs(log_dir, exist_ok=True)
        
        # 配置根日志器
        self.logger = logging.getLogger('alibaba')
        self.logger.setLevel(logging.DEBUG)
        
        # 清除现有的处理器
        self.logger.handlers.clear()
        
        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)
        
        # 文件处理器 - 所有日志
        file_handler = logging.FileHandler(
            os.path.join(log_dir, 'alibaba.log'),
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
        
        # 错误日志文件处理器
        error_handler = logging.FileHandler(
            os.path.join(log_dir, 'error.log'),
            encoding='utf-8'
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(formatter)
        self.logger.addHandler(error_handler)
        
        # 防止日志重复
        self.logger.propagate = False
    
    def debug(self, message: str, *args, **kwargs):
        """调试日志"""
        self.logger.debug(message, *args, **kwargs)
    
    def info(self, message: str, *args, **kwargs):
        """信息日志"""
        self.logger.info(message, *args, **kwargs)
    
    def warning(self, message: str, *args, **kwargs):
        """警告日志"""
        self.logger.warning(message, *args, **kwargs)
    
    def error(self, message: str, *args, **kwargs):
        """错误日志"""
        self.logger.error(message, *args, **kwargs)
    
    def critical(self, message: str, *args, **kwargs):
        """严重错误日志"""
        self.logger.critical(message, *args, **kwargs)
    
    def exception(self, message: str, *args, **kwargs):
        """异常日志（包含堆栈跟踪）"""
        self.logger.exception(message, *args, **kwargs)
    
    def log_function_call(self, func_name: str, args: tuple = (), kwargs: dict = None):
        """记录函数调用"""
        kwargs = kwargs or {}
        self.debug(f"调用函数: {func_name}(args={args}, kwargs={kwargs})")
    
    def log_user_action(self, action: str, user_id: str = None, details: str = ""):
        """记录用户操作"""
        user_info = f"用户 {user_id}" if user_id else "游客"
        self.info(f"用户操作: {user_info} - {action} - {details}")
    
    def log_business_event(self, event: str, details: str = ""):
        """记录业务事件"""
        self.info(f"业务事件: {event} - {details}")
    
    def log_security_event(self, event: str, details: str = ""):
        """记录安全事件"""
        self.warning(f"安全事件: {event} - {details}")
    
    def log_performance(self, operation: str, duration: float, details: str = ""):
        """记录性能信息"""
        self.info(f"性能: {operation} 耗时 {duration:.3f}s - {details}")


# 创建全局日志实例
logger = Logger()


def get_logger(name: str = None) -> logging.Logger:
    """获取日志器实例
    
    Args:
        name: 日志器名称，如果为None则返回根日志器
    
    Returns:
        logging.Logger: 日志器实例
    """
    if name:
        return logging.getLogger(f'alibaba.{name}')
    return logger.logger


# 便捷函数
def debug(message: str, *args, **kwargs):
    """调试日志"""
    logger.debug(message, *args, **kwargs)


def info(message: str, *args, **kwargs):
    """信息日志"""
    logger.info(message, *args, **kwargs)


def warning(message: str, *args, **kwargs):
    """警告日志"""
    logger.warning(message, *args, **kwargs)


def error(message: str, *args, **kwargs):
    """错误日志"""
    logger.error(message, *args, **kwargs)


def critical(message: str, *args, **kwargs):
    """严重错误日志"""
    logger.critical(message, *args, **kwargs)


def exception(message: str, *args, **kwargs):
    """异常日志"""
    logger.exception(message, *args, **kwargs)
